# !coding=utf-8
# @Time:2020/10/3010:11
# @Auth: loki
from py2neo import *
from collections import Iterable
from pandas.core.frame import DataFrame

#连接数据neo4j
def neo4j_connect(url,user,password):
    try:
        graph=Graph(url,username=user,password=password)
    except Exception as e :
        print u'neo4j连接失败{}.'.format(e)
        graph=False
    return graph


#创建单标签节点
def create_node_lable(graph):
    if graph:
        # "节点名称",属性="属性值"
        node1=Node("person",name="zhangsan",age="18")
        try:
            graph.create(node1)
        except Exception as e :
            print u'创建失败{}.'.format(e)

#创建多标签节点
def create_node_lables(graph):
    if graph:
        node2=Node("person","son","boy",name="daming",age=1)
        try:
            graph.create(node2)
        except Exception as e :
            print u'创建失败{}.'.format(e)

#创建节点关系
def add_rel(graph):
    if graph:
        node1=Node("person","boy",name="father1",age=44)
        graph.create(node1)   #不用先创建节点，直接在rel中创建，也可以节点关系同时构建
        node2=Node("person","boy","son",name="son2",age=33)
        graph.create(node2)
        rel=Relationship(node1,"Father",node2)
        graph.create(rel)


def query_by_py2neo(graph):
    if graph:
        matcher=NodeMatcher(graph)
        # result=matcher.match("person",name="xiaoming")
        result=matcher.match(rel_type="Father").first()
        print result
        for i in result:
            print i
        # print(result_dataframe)


# 修改节点属性
def model_by(graph):
    if graph:
        matcher=NodeMatcher(graph)
        result=matcher.match(name="xiaoming2").first()
        result.update({'name':'xiaoming3'})
        # result.update(name="xiaoming3")
        graph.push(result)


def query_by_cypher(graph):
    result=graph.run('match (p:person) where p.name="xiaoming" return p').data
    print(isinstance(result, Iterable))


def main ():
    graph=neo4j_connect("http://localhost:7474/","neo4j","adminadmin")
    if graph:
        # create_node_lable(graph)
        # create_node_lables(graph)
        # add_rel(graph)
        # query(graph)
        query_by_py2neo(graph)
        # query_by_cypher(graph)
        # model_by(graph)
if __name__ == '__main__':
    main()